﻿Public Class Form3
    Private Shared _instance As Form3
    Dim cbo_rti1 As RefTypeItem
    Public Shared ReadOnly Property Instance() As Form3
        Get
            If _instance Is Nothing OrElse _instance.IsDisposed Then
                _instance = New Form3
            End If
            Return _instance
        End Get

    End Property

    ''' <summary>
    ''' 刷新数据
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btnRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRefresh.Click
        If sender.Text = "取消" Then
            sender.Text = "正在取消..."
            sender.Enabled = False
            bwSearch.CancelAsync()
            Exit Sub
        End If

        If CheckValidate() = False Then
            Exit Sub
        End If

        Me.DataGridView1.DataSource = Nothing
        Me.DataGridView1.Columns.Clear()

        BeforeRefreshControlState()
        Me.bwSearch.RunWorkerAsync(New Object() {Me.cboRef.SelectedItem, Me.dtpFrom.Value, Me.dtpTo.Value, Me.cboIntevalType.Text.Trim, Me.cboSecond.Text, Me.nudMinute.Value, Me.nudHour.Value})

    End Sub
    Private Sub BeforeRefreshControlState()
        'Me.DataGridView1.Cursor = Cursors.WaitCursor
        'Me.btnRefresh.Enabled = False
        Me.btnRefresh.Text = "取消"
        Me.dtpFrom.Enabled = False
        Me.dtpTo.Enabled = False
        Me.btnExport.Enabled = False
        Me.cboIntevalType.Enabled = False
        Me.cboRef.Enabled = False
        Me.cboSecond.Enabled = False
        Me.nudHour.Enabled = False
        Me.nudMinute.Enabled = False
        Me.btnPrint.Enabled = False
        Me.pnlSearch.Visible = True
    End Sub
    Private Sub AfterRefreshControlState()
        'Me.pnlSearch.Visible = False
        Me.cboIntevalType.Enabled = True
        Me.cboRef.Enabled = True
        Me.cboSecond.Enabled = True
        Me.nudHour.Enabled = True
        Me.nudMinute.Enabled = True
        'Me.btnExport.Enabled = True
        'Me.btnPrint.Enabled = True
        Me.dtpFrom.Enabled = True
        Me.dtpTo.Enabled = True
        Me.btnRefresh.Enabled = True
        Me.btnRefresh.Text = "查询"
        'Me.DataGridView1.Cursor = Cursors.Default
    End Sub

    ''' <summary>
    ''' 刷新数据
    ''' </summary>
    ''' <remarks></remarks>
    Private Function RefreshData(ByVal argument As Object) As Object
        Dim cbo_rti As RefTypeItem = argument(0)
        Dim dtpFromValue As Date = argument(1)
        Dim dtpToValue As Date = argument(2)
        Dim IntevalType As String = argument(3)
        Dim _Second As Integer
        Dim AI_ColumnName As String
        Dim IsFind As Boolean

        Try
            _Second = Convert.ToInt32(argument(4))
        Catch ex As Exception
            _Second = 0
        End Try
        Dim _Minute As Integer = argument(5)
        Dim _Hour As Integer = argument(6)
        Dim strSql As String
        'Dim cbo_rti As RefTypeItem = CType(cboRef.SelectedItem, RefTypeItem)
        Dim apts As AiPortTypeService = New AiPortTypeService(cbo_rti)
        Dim alarmstatus_DoorValid As Boolean = False
        Dim alarmstatus_LosPowerValid As Boolean = False
        Dim alarmstatus_RefAlarmValid As Boolean = False
        Dim alarmstatus_SoundAlarmValid As Boolean = False

        strSql = String.Format("select hDate")


        For Each apti As AiPortTypeItem In apts.GetAiGroupList()
            If String.IsNullOrEmpty(apti.PortName) = False AndAlso apti.PortNo <> 0 Then '如果AI名称不为空并且端口号不为0
                strSql &= String.Format(",{0}", "AI" & Trim(apti.PortNo.ToString))
                ' Dim item As New AIItem

            End If
        Next

        'If is_firstrun = True Then '当前冷库没有配置AI
        '    msg.Show("指定冷库尚未配置数据端口")
        'End If

        Dim diopts As DiDoPortTypeService = New DiDoPortTypeService(cbo_rti)

        Dim DoorState_tablename = String.Format("Ref{0}_DoorState", cbo_rti.RefId.ToString)
        Dim LostPowerState_tablename = String.Format("Ref{0}_LostPowerState", cbo_rti.RefId.ToString)
        Dim RefAlarmState_tablename = String.Format("Ref{0}_RefAlarmState", cbo_rti.RefId.ToString)
        Dim SoundOutputState_tablename = String.Format("Ref{0}_SoundOutputState", cbo_rti.RefId.ToString)

        For Each diopti As DiDoPortTypeItem In diopts.GetDioGroupList()
            If diopti.DoorStatusPort >= 1 Then
                strSql &= String.Format("," & DoorState_tablename)
                alarmstatus_DoorValid = True
            End If

            If diopti.LostPowerPort >= 1 Then
                strSql &= String.Format("," & LostPowerState_tablename)
                alarmstatus_LosPowerValid = True
            End If

            If diopti.RefAlarmPort >= 1 Then
                strSql &= String.Format("," & RefAlarmState_tablename)
                alarmstatus_RefAlarmValid = True
            End If

            If diopti.SoundAlarmPort >= 1 Then
                strSql &= String.Format("," & SoundOutputState_tablename)
                alarmstatus_SoundAlarmValid = True
            End If
        Next

        strSql &= String.Format(" From tbccHDData_{0}_{1} Where hDate>='{2}' and hDate<='{3}' order by hDate", Trim(cbo_rti.ProjectID).Replace("-", "_"), cbo_rti.NetId, UtilityClass.GetDateString(dtpFromValue), UtilityClass.GetDateString(dtpToValue))

        Dim ds As DataSet = Nothing

        Try
            ds = SqlHelper.ExecuteDataset(strSql, Nothing)

            If ds.Tables.Count = 0 OrElse ds.Tables(0).Rows.Count = 0 Then
                ds.Clear() : ds.Dispose() : ds = Nothing
                Return Nothing
            End If

            '时间间隔数据
            Dim iSeconds As Integer = HIST_SAVE_INTERVAL_TIME

            'Select Case IntevalType
            '    Case "秒"
            '        If _Second > 0 Then
            '            iSeconds = _Second
            '        End If

            '    Case "分钟"
            '        iSeconds = _Minute * 60

            '    Case "小时"
            '        iSeconds = _Hour * 3600

            '    Case Else
            '        Return Nothing
            'End Select

            Dim dtStart As DateTime
            dtStart = AdjustDateTime(dtpFromValue)

            Dim proIndex As Integer = 0
            Dim dtTmp As DateTime
            For Each r As DataRow In ds.Tables(0).Rows
                If Me.bwSearch.CancellationPending Then
                    Return Nothing '取消查询
                End If
                dtTmp = r("hdate")
                If dtTmp.Subtract(dtStart).TotalSeconds Mod iSeconds <> 0 Then
                    r.Delete()
                Else
                    r = r

                    IsFind = False
                    For Each apti As AiPortTypeItem In apts.GetAiGroupList() '不显示未激活冷库的的数据
                        If String.IsNullOrEmpty(apti.PortName) = False AndAlso apti.PortNo <> 0 Then '如果AI名称不为空并且端口号不为0
                            AI_ColumnName = String.Format("{0}", "AI" & Trim(apti.PortNo.ToString))
                            If Not IsDBNull(r(AI_ColumnName)) Then 'AI端口存在
                                If r(AI_ColumnName) = INVALID_DATA Then
                                    r.Delete()
                                    IsFind = True
                                    Exit For
                                End If
                            End If
                        End If
                    Next

                    If IsFind = True Then
                        Continue For
                    End If

                    If alarmstatus_DoorValid = True Then
                        If Not IsDBNull(r(DoorState_tablename)) Then '库门开关状态
                            If r(DoorState_tablename) = g_On Then
                                r(DoorState_tablename) = "开"
                            Else
                                r(DoorState_tablename) = "关"
                            End If
                        End If
                    End If

                    If alarmstatus_LosPowerValid = True Then
                        If Not IsDBNull(r(LostPowerState_tablename)) Then '缺项报警状态
                            If r(LostPowerState_tablename) = g_On Then
                                r(LostPowerState_tablename) = "报警"
                            Else
                                r(LostPowerState_tablename) = "正常"
                            End If
                        End If
                    End If

                    If alarmstatus_RefAlarmValid = True Then
                        If Not IsDBNull(r(RefAlarmState_tablename)) Then '冷库报警状态
                            If r(RefAlarmState_tablename) = g_On Then
                                r(RefAlarmState_tablename) = "报警"
                            Else
                                r(RefAlarmState_tablename) = "正常"
                            End If
                        End If
                    End If

                    If alarmstatus_SoundAlarmValid = True Then
                        If Not IsDBNull(r(SoundOutputState_tablename)) Then '声光报警状态
                            If r(SoundOutputState_tablename) = g_On Then
                                r(SoundOutputState_tablename) = "报警"
                            Else
                                r(SoundOutputState_tablename) = "正常"
                            End If
                        End If
                    End If

                End If
                proIndex += 1
                ReportProgress((proIndex / ds.Tables(0).Rows.Count) * 100) '报告进度
            Next



            ds.AcceptChanges()


            If ds.Tables(0).Rows.Count = 0 Then
                ds.Clear() : ds.Dispose() : ds = Nothing

                Return Nothing

            End If

        Catch ex As Exception
            'msg.Show("指定时间范围没有数据,请重新设置时间范围")
            If ds IsNot Nothing Then
                ds.Clear() : ds.Dispose() : ds = Nothing
            End If
        End Try

        Return ds
    End Function

    ''' <summary>
    ''' 检查时间范围是否合法
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function CheckValidate() As Boolean
        If Me.dtpTo.Value < Me.dtpFrom.Value Then
            msg.ShowWarning("起始时间不能大于终止时间。")
            Me.dtpFrom.Focus()
            Return False
        End If

        '限制查询的历史记录数量
        Dim ratio As Integer = 1
        Select Case Me.cboIntevalType.Text.Trim()
            Case "秒"
                ratio = 1
            Case "分钟"
                ratio = 6

            Case "小时"
                ratio = 360
            Case Else
                Return False
        End Select

        If Me.dtpTo.Value > Me.dtpFrom.Value.AddDays(7 * ratio) Then
            msg.ShowWarning(String.Format("查询的时间间隔不能超过{0}天", 7 * ratio))
            Me.dtpFrom.Focus()
            Return False
        End If

        Return True
    End Function

    Private Function AdjustDateTime(ByVal dt As DateTime) As DateTime
        Return dt.AddSeconds(-dt.Second Mod HIST_SAVE_INTERVAL_TIME)
    End Function

    Private Sub HDViewForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.DataGridView1.AutoGenerateColumns = False

        Me.cboIntevalType.SelectedIndex = 2
        Me.cboRef.SelectedIndex = -1

        Dim dt As DateTime = UtilityClass.GetDateString(Now)
        dtpTo.Value = dt
        dtpFrom.Value = dt.ToLongDateString()
        'dtpFrom.Value = dtpFrom.Value.AddMonths(-1)
        dtpFrom.Value = dtpFrom.Value.AddDays(-1)
        LoadRef()

    End Sub

    Private Sub LoadRef()
        Dim rts As RefTypeService = New RefTypeService(MainForm.pi)

        For Each rti As RefTypeItem In rts.GeRefGroupList()
            cboRef.Items.Add(rti)
        Next


        cboRef.SelectedIndex = -1
        btnRefresh.Enabled = False
        btnPrint.Enabled = False
    End Sub
    Private Sub btnExport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExport.Click
        'If Me.cboAI.SelectedIndex < 0 Then
        '    msg.Show("请选择要修改的探头")
        '    cboAI.Focus()
        '    Exit Sub
        'End If
        'Me.Cursor = Cursors.WaitCursor

        'ModifyData()

        'Me.Cursor = Cursors.Default

        If Me.nudMax.Value <= nudMin.Value Then
            msg.Show("最大值必须大于最小值")
            Me.nudMax.Focus()
            Exit Sub
        End If

        Me.Cursor = Cursors.WaitCursor
        
        ModifyData2()
        
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub ModifyData2()
        Dim dt As DataTable
        dt = Me.DataGridView1.DataSource

        If dt Is Nothing OrElse dt.Rows.Count < 3 Then
            Exit Sub
        End If

        If Me.cboAI.SelectedIndex < 0 Then
            msg.Show("请选择要修改的探头")
            cboAI.Focus()
            Exit Sub
        End If
        

        '探头
        Dim col As String = CType(Me.cboAI.SelectedItem, AIItem).FieldName
        
        






        '最小值
        Dim min As Double = Me.nudMin.Value

        '最大值
        Dim max As Double = Me.nudMax.Value

        '周期（分钟）
        Dim iCycle As Integer
        iCycle = Me.nudCircle.Value

        '上升周期
        Dim iupCycle As Integer
        iupCycle = Me.nudupcircle.Value

        '下降周期
        Dim idwCycle As Integer
        idwCycle = iCycle - iupCycle

        If iupCycle >= iCycle Then
            msg.Show("上升周期必须小于整个周期")
            Exit Sub
        End If

        '数据行数
        Dim count As Integer = dt.Rows.Count

        '每个周期数据的行数
        Dim upcycleCount, dwcycleCount As Integer
        upcycleCount = iupCycle * 6
        dwcycleCount = idwCycle * 6

        '每行数据的差值
        Dim updelta, dwdelta As Double
        updelta = (max - min) / upcycleCount
        dwdelta = (max - min) / dwcycleCount

        Dim index As Integer

        Dim dir As Integer
        Dim basevalue As Double = dt.Rows(0)(col)

        If Me.nudDown.Checked Then
            dir = -1

            index = (max - basevalue) / dwdelta
            basevalue = max
        Else
            dir = 1

            index = (basevalue - min) / updelta
            basevalue = min
        End If

        For i As Integer = 0 To count - 1
            Dim r As DataRow
            r = dt.Rows(i)

            Dim Curvalue As Single
            If dir = 1 Then '上升
                If CInt(col.Remove(0, 2)) >= 10 Then
                    Curvalue = basevalue + updelta * index * dir + GetRand1()
                Else
                    Curvalue = basevalue + updelta * index * dir

                End If



            ElseIf dir = -1 Then '下降
                If CInt(col.Remove(0, 2)) >= 10 Then
                    Curvalue = basevalue + updelta * index * dir + GetRand1()
                Else
                    Curvalue = basevalue + updelta * index * dir

                End If
            End If

            If Curvalue > max Then
                Curvalue = max
                basevalue = max
                index = 0
                dir = -1
            ElseIf Curvalue < min Then
                Curvalue = min
                basevalue = min
                index = 0
                dir = 1
            End If

            r(col) = Format(Curvalue + GetRand(), "0.00")

            index += 1
        Next

    End Sub
    Private Function GetRand() As Double
        Dim dd As Single = 0
        If g_rand.Next(1, 100) Mod 10 = 1 Then
            dd = 0.01
        End If
        If g_rand.Next(1, 100) Mod 20 = 1 Then
            dd = 0.02
        End If
        If g_rand.Next(1, 100) Mod 30 = 1 Then
            dd = 0.03
        End If
        If g_rand.Next(1, 100) Mod 40 = 1 Then
            dd = 0.04
        End If
        If g_rand.Next(1, 100) Mod 50 = 1 Then
            dd = 0.05
        End If
        If g_rand.Next(1, 100) Mod 60 = 1 Then
            dd = -0.01
        End If
        If g_rand.Next(1, 100) Mod 70 = 1 Then
            dd = -0.02
        End If
        If g_rand.Next(1, 100) Mod 80 = 1 Then
            dd = -0.03
        End If
        If g_rand.Next(1, 100) Mod 90 = 1 Then
            dd = -0.04
        End If

        Return dd
    End Function
    Private Function GetRand1() As Double
        Dim dd As Single = 0
        If g_rand.Next(1, 100) Mod 10 = 1 Then
            dd = 0.7
        End If
        If g_rand.Next(1, 100) Mod 20 = 1 Then
            dd = 0.8
        End If
        If g_rand.Next(1, 100) Mod 30 = 1 Then
            dd = 0.9
        End If
        If g_rand.Next(1, 100) Mod 40 = 1 Then
            dd = 1.1
        End If
        If g_rand.Next(1, 100) Mod 50 = 1 Then
            dd = 1.2
        End If
        If g_rand.Next(1, 100) Mod 60 = 1 Then
            dd = -0.7
        End If
        If g_rand.Next(1, 100) Mod 70 = 1 Then
            dd = -0.5
        End If
        If g_rand.Next(1, 100) Mod 80 = 1 Then
            dd = -0.8
        End If
        If g_rand.Next(1, 100) Mod 90 = 1 Then
            dd = -1
        End If

        Return dd
    End Function
    Private Class AIItem
        Public header As String
        Public FieldName As String

        Public Overrides Function ToString() As String
            Return header
        End Function
    End Class


    Dim cols(100) As String
    Dim headers(100) As String



    Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click
        Me.Cursor = Cursors.WaitCursor
        'Me.btnSave.Enabled = False
        'Me.btnModify.Enabled = False
        'Me.btnRefresh.Enabled = False

        SaveData()

        'Me.btnSave.Enabled = True
        'Me.btnModify.Enabled = True
        'Me.btnRefresh.Enabled = True


        Me.Cursor = Cursors.Default
    End Sub
    Private Sub SaveData()
        Dim dt As DataTable
        dt = Me.DataGridView1.DataSource

        If dt Is Nothing Then
            Exit Sub
        End If

        ' Dim tmp As Single
        Dim str As String = ""

        

        Try
            Dim tic As New TBCC.Utility.TranstrationItem()

            For Each r As DataRow In dt.Rows
                If r.RowState = DataRowState.Modified Then
                    SaveRow(r, tic)
                End If
            Next

            ' SqlHelper.ExecuteTranstration(tic)

            msg.Show("保存完成")
        Catch ex As Exception
            Debug.WriteLine(ex.Message)
            msg.Show("保存失败")
        End Try
    End Sub
    Private _i As Integer = 0
    Private Sub SaveRow(ByVal r As DataRow, ByVal tic As TranstrationItem)
        Dim strSql As String
        Dim ai As String
        'Dim aicount As String
        Dim n As Integer = 0
        Dim i As Integer = 0
        Dim ainum As New ArrayList
        Dim apts As AiPortTypeService = New AiPortTypeService(cbo_rti1)
        'strSql = "Update tbccHDData_{0}_{1} set AI1=?,AI2=?,AI3=?,AI4=?,AI5=?,AI6=?,AI7=?,AI8=?," _
        '        & "AI9=?,AI10=?,AI11=?,AI12=?,AI13=?,AI14=?,AI15=?,AI16=?," _
        '        & "TBCCAI1=?,TBCCAI2=?,TBCCAI3=?,TBCCAI4=?,TBCCAI5=?,TBCCAI6=?,TBCCAI7=?,TBCCAI8=?,TBCCAI9=?,TBCCAI10=?,TBCCAI11=?,TBCCAI12=? where hDate=? --"

        'strSql = "Update tbccHDData set AI1=?,AI2=?,AI3=?,AI4=?,AI5=?,AI6=?,AI7=?,AI8=?," _
        '        & "AI9=?,AI10=?,AI11=?,AI12=?,AI13=?,AI14=?,AI15=?,AI16=?," _
        '        & "TBCCAI1=?,TBCCAI2=?,TBCCAI3=?,TBCCAI4=?,TBCCAI5=?,TBCCAI6=?,TBCCAI7=?,TBCCAI8=?,TBCCAI9=?,TBCCAI10=?,TBCCAI11=?,TBCCAI12=? where hDate=? --"
        ''From tbccHDData_{0}_{1} Where hDate>='{2}' and hDate<='{3}' order by hDate", Trim(cbo_rti.ProjectID).Replace("-", "_"), cbo_rti.NetId, UtilityClass.GetDateString(dtpFromValue), UtilityClass.GetDateString(dtpToValue))

        strSql = String.Format("Update tbccHDData_{0}_{1} set ", Trim(cbo_rti1.ProjectID).Replace("-", "_"), cbo_rti1.NetId)
        i = apts.GetAiGroupList.Count
        For Each apti As AiPortTypeItem In apts.GetAiGroupList()
            ai = String.Format("AI" & Trim(apti.PortNo.ToString), apti.PortName)
            ainum.Add(ai)
            n += 1
            If String.IsNullOrEmpty(apti.PortName) = False AndAlso apti.PortNo <> 0 Then '如果AI名称不为空并且端口号不为0
                strSql &= String.Format("{0}", "AI" & Trim(apti.PortNo.ToString))
                strSql &= String.Format("=?")
                If apts.GetAiGroupList.Count = n Then
                Else

                    strSql &= String.Format(",")
                End If
                'strSql &= String.Format(",")

                'Dim item As New AIItem

            End If
        Next
        n = 0

        strSql &= String.Format(" where hDate=? --")
        Dim p(i) As MySql.Data.MySqlClient.MySqlParameter
        For j As Integer = 0 To p.Length - 1
            p(j) = New MySql.Data.MySqlClient.MySqlParameter()
        Next

        'For j As Integer = 1 To 16
        '    p(j - 1).Value = r("AI" & j)
        'Next

        For k As Integer = 0 To ainum.Count - 1
            'aicount = ainum.Item(k)
            p(k).Value = r(ainum.Item(k))
        Next
        p(i).Value = r("hDate")

        'p(28).Value = r("hdate")

        '修改数据
        'SqlHelper.ExecuteNonQuery(strSql, Nothing)
        SqlHelper.ExecuteNonQuery(strSql, p)
        'tic.Add(strSql & _i, p)
        '_i += 1


    End Sub



    Private Sub cboIntevalType_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboRef.SelectedIndexChanged, cboIntevalType.SelectedIndexChanged
        Me.btnPrint.Enabled = False

        HideAll()

        Select Case Me.cboIntevalType.SelectedIndex
            Case 0
                'second
                Me.cboSecond.Visible = True
                Me.cboSecond.SelectedIndex = 0

            Case 1
                'minute
                Me.nudMinute.Visible = True
                Me.nudMinute.Value = 1

            Case 2
                'hour
                Me.nudHour.Visible = True
                Me.nudHour.Value = 1

        End Select

        If cboRef.SelectedIndex <> -1 Then
            btnRefresh.Enabled = True
        End If

    End Sub

    Private Sub HideAll()
        Me.cboSecond.Visible = False
        Me.nudHour.Visible = False
        Me.nudMinute.Visible = False
    End Sub


    Private Sub cboSecond_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboSecond.SelectedIndexChanged
        Me.btnPrint.Enabled = False
    End Sub

    Private Sub nudHour_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles nudHour.ValueChanged
        Me.btnPrint.Enabled = False
    End Sub

    Private Sub nudMinute_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles nudMinute.ValueChanged
        Me.btnPrint.Enabled = False
    End Sub

    Private Sub dtpFrom_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtpFrom.ValueChanged
        Me.btnPrint.Enabled = False
    End Sub

    Private Sub dtpTo_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtpTo.ValueChanged
        Me.btnPrint.Enabled = False
    End Sub

    Private Delegate Sub VoidMethodHandler(ByVal obj As Object)
    Private Sub bwSearch_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bwSearch.DoWork
        Dim ds As DataSet
        e.Result = New Object() {True, Nothing}

        '设置状态
        Dim str As String = String.Format("正在查询{0}历史数据……", e.Argument(0))
        If Me.InvokeRequired Then
            Me.Invoke(New VoidMethodHandler(AddressOf SetSearchState), str)
        Else
            SetSearchState(str)
        End If

        '查询数据
        ds = RefreshData(e.Argument)
        cbo_rti1 = e.Argument(0)

        '添加数据至DataGridView
        If ds IsNot Nothing Then
            Dim obj As Object = New Object() {e.Argument(0), ds}
            If Me.InvokeRequired Then
                Me.Invoke(New VoidMethodHandler(AddressOf AddDataToGridView), obj)
            Else
                AddDataToGridView(obj)
            End If
        Else
            e.Result(0) = False '无数据
        End If

        e.Result(1) = Me.bwSearch.CancellationPending
    End Sub

    Private Sub bwSearch_ProgressChanged(ByVal sender As System.Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bwSearch.ProgressChanged
        Me.pbSearch.Value = e.ProgressPercentage
    End Sub

    Private Sub bwSearch_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bwSearch.RunWorkerCompleted
        Me.pnlSearch.Visible = False

        If e.Result(0) = True Then
            Me.btnExport.Enabled = True
            Me.btnPrint.Enabled = True
        ElseIf Not e.Result(1) Then '过滤取消操作
            Me.btnExport.Enabled = False
            Me.btnPrint.Enabled = False
            msg.Show("指定时间范围没有数据,请重新设置时间范围")
        End If

        AfterRefreshControlState()
        GC.Collect()

        If e.Result(1) Then
            msg.Show("操作已取消")
        End If

    End Sub
    Private Sub AddDataGridViewColumns(ByVal obj As Object)
        Dim m_index As Integer
        Dim cbo_rti As RefTypeItem = obj
        Dim apts As AiPortTypeService = New AiPortTypeService(cbo_rti)

        '时间列
        m_index = Me.DataGridView1.Columns.Add("hDate", "时间")
        Me.DataGridView1.Columns(m_index).DataPropertyName = "hDate"
        Me.DataGridView1.Columns(m_index).AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells

        'AI列
        For Each apti As AiPortTypeItem In apts.GetAiGroupList()
            If String.IsNullOrEmpty(apti.PortName) = False AndAlso apti.PortNo <> 0 Then '如果AI名称不为空并且端口号不为0
                m_index = Me.DataGridView1.Columns.Add("AI" & Trim(apti.PortNo.ToString), apti.PortName)
                Me.DataGridView1.Columns(m_index).DataPropertyName = "AI" & Trim(apti.PortNo.ToString)
                'Me.DataGridView1.Columns(m_index).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
            End If
        Next


        Me.Panel1.Enabled = True
        Me.cboAI.Items.Clear()
        For Each col As DataGridViewColumn In Me.DataGridView1.Columns
            If col.Visible = True Then
                Dim item As New AIItem
                item.FieldName = col.DataPropertyName
                If col.HeaderText = "时间" Then
                Else
                    item.header = col.HeaderText
                    cboAI.Items.Add(item)

                End If


            End If
        Next

       
    End Sub
    Private Sub AddDataToGridView(ByVal obj As Object)
        AddDataGridViewColumns(obj(0))
        Me.DataGridView1.DataSource = obj(1).Tables(0)
    End Sub
    Private Sub SetSearchState(ByVal obj As Object)
        Me.lblSearchState.Text = obj
    End Sub
    Private Sub ReportProgress(ByVal value As Integer)
        If Me.InvokeRequired Then
            Me.Invoke(New VoidMethodHandler(AddressOf ReportProgressMethod), value)
        Else
            ReportProgressMethod(value)
        End If
    End Sub
    Private Sub ReportProgressMethod(ByVal obj As Object)
        Me.bwSearch.ReportProgress(obj)
    End Sub

    Private Sub HDViewForm_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        DisposeBackWorker()
    End Sub

    Private Sub DisposeBackWorker()
        If Me.bwSearch IsNot Nothing Then
            Me.bwSearch.CancelAsync()
            Me.bwSearch.Dispose() : Me.bwSearch = Nothing
        End If
        GC.Collect()
    End Sub

    Private Sub DataGridView1_CellPainting(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellPaintingEventArgs) Handles DataGridView1.CellPainting
        If e.ColumnIndex >= 0 AndAlso e.RowIndex >= 0 Then
            If Me.DataGridView1.Columns(e.ColumnIndex).Name.StartsWith("Ref") Then
                Dim cell As DataGridViewCell = Me.DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex)
                If cell.Value.Equals("报警") Then
                    cell.Style.ForeColor = Color.Red
                End If
            End If
        End If
    End Sub

    Private Sub Label4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label4.Click

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    

        Me.Cursor = Cursors.WaitCursor

        AddData()

        Me.Cursor = Cursors.Default

    End Sub
    Public Sub AddData()
        Dim cbo_rti As RefTypeItem = Me.cboRef.SelectedItem
        Dim strSql As String
        Dim tic As New TranstrationItem

        Dim dtto As DateTime
        dtto = Me.dtpto2.Value
        Dim dtTmp As DateTime
        dtTmp = Me.dtpform1.Value

        Dim dtftmp As DateTime
        Dim dttotmp As DateTime

        dtftmp = Me.dtpFrom.Value
        dttotmp = Me.dtpTo.Value



        strSql = String.Format("Select * From tbcchddata_526f9a3b_7d20_4a10_93e8_f9845a2bf985_1 where hDate>='{0}'and hDate <='{1}'order by hDate", UtilityClass.GetDateString(dtftmp), UtilityClass.GetDateString(dttotmp))
        Dim ds As DataSet


        ds = TBCC.Utility.SqlHelper.ExecuteDataset(strSql, Nothing)


        'Dim id As Integer
        Dim ai1 As String
        Dim ai2 As String
        Dim ai3 As String
        Dim ai4 As String
        Dim ai5 As String
        Dim ai6 As String
        Dim ai7 As String
        Dim ai8 As String
        Dim ai9 As String
        Dim ai10 As String
        Dim ai11 As String
        Dim ai12 As String
        Dim Ref1_RefAlarmState As String
        Dim Ref1_LostPowerState As String
        Dim Ref1_SoundOutputState As String
        Dim Ref1_DoorState As String
        Dim Ref2_RefAlarmState As String
        Dim Ref2_LostPowerState As String
        Dim Ref2_SoundOutputState As String
        Dim Ref2_DoorState As String
        Dim Ref3_RefAlarmState As String
        Dim Ref3_LostPowerState As String
        Dim Ref3_SoundOutputState As String
        Dim Ref3_DoorState As String
        Dim Ref4_RefAlarmState As String
        Dim Ref4_LostPowerState As String
        Dim Ref4_SoundOutputState As String
        Dim Ref4_DoorState As String


        'Do Until dtTmp = dtto
        For Each r As DataRow In ds.Tables(0).Rows
            'id = r("id")
            dtTmp = dtTmp.AddSeconds(10)
            If dtTmp = dtto Then
                Exit For
            End If
            ai1 = r("AI1")
            ai2 = r("AI2")
            ai3 = r("AI3")
            ai4 = r("AI4")
            ai5 = r("AI5")
            ai6 = r("AI6")
            ai7 = r("AI7")
            ai8 = r("AI8")
            ai9 = r("AI9")
            ai10 = r("AI10")
            ai11 = r("AI11")
            ai12 = r("AI12")
            Ref1_RefAlarmState = r("Ref1_RefAlarmState")
            Ref1_LostPowerState = r("Ref1_LostPowerState")
            Ref1_SoundOutputState = r("Ref1_SoundOutputState")
            Ref1_DoorState = r("Ref1_DoorState")
            Ref2_RefAlarmState = r("Ref2_RefAlarmState")
            Ref2_LostPowerState = r("Ref2_LostPowerState")
            Ref2_SoundOutputState = r("Ref2_SoundOutputState")
            Ref2_DoorState = r("Ref2_DoorState")
            Ref3_RefAlarmState = r("Ref3_RefAlarmState")
            Ref3_LostPowerState = r("Ref3_LostPowerState")
            Ref3_SoundOutputState = r("Ref3_SoundOutputState")
            Ref3_DoorState = r("Ref3_DoorState")
            Ref4_RefAlarmState = r("Ref4_RefAlarmState")
            Ref4_LostPowerState = r("Ref4_LostPowerState")
            Ref4_SoundOutputState = r("Ref4_SoundOutputState")
            Ref4_DoorState = r("Ref4_DoorState")




            strSql = String.Format("Insert Into tbcchddata_526f9a3b_7d20_4a10_93e8_f9845a2bf985_1(hDate,AI1,AI2,AI3,AI4,AI5,AI6,AI7,AI8,AI9,AI10,AI11,AI12," _
                            & "Ref1_RefAlarmState,Ref1_LostPowerState,Ref1_SoundOutputState,Ref1_DoorState,Ref2_RefAlarmState,Ref2_LostPowerState,Ref2_SoundOutputState,Ref2_DoorState," _
                            & "Ref3_RefAlarmState,Ref3_LostPowerState,Ref3_SoundOutputState,Ref3_DoorState,Ref4_RefAlarmState,Ref4_LostPowerState,Ref4_SoundOutputState,Ref4_DoorState)" _
                                & " Values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}','{17}','{18}','{19}','{20}','{21}','{22}','{23}','{24}','{25}','{26}','{27}','{28}') ", _
                                 UtilityClass.GetDateString(dtTmp), ai1, ai2, ai3, ai4, ai5, ai6, ai7, ai8, ai9, ai10, ai11, ai12, Ref1_RefAlarmState, Ref1_LostPowerState, Ref1_SoundOutputState, Ref1_DoorState, Ref2_RefAlarmState, Ref2_LostPowerState, Ref2_SoundOutputState, Ref2_DoorState, Ref3_RefAlarmState, _
                                Ref3_LostPowerState, Ref3_SoundOutputState, Ref3_DoorState, Ref4_RefAlarmState, Ref4_LostPowerState, Ref4_SoundOutputState, Ref4_DoorState)

            tic.Add(strSql, Nothing)

        Next

        SqlHelper.ExecuteTranstration(tic)
        ' Loop


    End Sub
End Class